package me.xiaolei.testfloatwindow

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.provider.Settings
import android.util.Log
import android.widget.TextView
import me.xiaolei.float_window.*

class MainActivity : AppCompatActivity()
{
    private var callback: OnPermissionResult? = null
    private val helloView: TextView by lazy { findViewById(R.id.hello_view) }

    private val connect = object : ServiceConnection, PermissionAdapter
    {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?)
        {
            Log.e("XIAOLEI", "onServiceConnected:$service")
            val binder = service as? FloatBinder ?: return
            binder.with(R.layout.layout_float_view)
                .permissionAdapter(this) // 悬浮窗权限适配器
                .size(100, 100) // 大小
                .alpha(0.8f) // 透明度
                .draggable(true) // 可拖拽
                .position(Direction.BOTTOM_OUTER, helloView) // 初始位置
                .onShow { holder -> // 显示的事件
                    val appName = holder.get<TextView>(R.id.app_name)
                    appName.text = "显示/启动咯"
                }
                .onUpdate { bundle, holder -> // 更新数据的事件

                }
                .build()
                .show()
        }

        override fun onServiceDisconnected(name: ComponentName?) = Unit

        /**
         * 是否有权限
         */
        override fun hasPermission(context: Context): Boolean
        {
            return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            {
                Settings.canDrawOverlays(context)
            } else
            {
                false
            }
        }

        /**
         * 请求权限
         */
        override fun startRequestPermission(context: Context, callback: OnPermissionResult)
        {
            val intent = Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION)
            startActivity(intent)
            this@MainActivity.callback = callback
        }
    }

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val intent = Intent(this, FloatWindowService::class.java)
        bindService(intent, connect, Context.BIND_AUTO_CREATE)
    }

    override fun onResume()
    {
        val success = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            Settings.canDrawOverlays(this)
        } else
        {
            false
        }
        callback?.onResult(success)
        super.onResume()
    }
}